//
//  ByUIOrderPayVC.m
//  itboye_shop_ios
//
//  Created by pro on 17/2/10.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIOrderPayVC.h"

// cell
#import "ByCellOrderPayType.h"          // 支付方式

// api
#import "ByApiPay.h"                    // 支付接口

//#import "ByNetWechatPayModel.h"
//#import "ByNetPayModel.h"
//#import "ByNetWechatPayModel.h"
//
//
//#import "ByNetPayApi.h"
//#import "ByNetWechatPayApi.h"
//#import "ByNetAliPayApi.h"
//#import "ByNetWalletApi.h"
//#import "ByWalletPasswordManager.h"

@interface ByUIOrderPayVC () <UITableViewDelegate, UITableViewDataSource>

// view
@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) UIView *headerView;

// data
@property (nonatomic, copy) NSArray *infoDicArray;
@property (nonatomic, strong) NSMutableArray *selectArray;

// timer
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation ByUIOrderPayVC
{
    NSInteger _second;
}

#pragma mark - 懒加载
- (NSArray *)infoDicArray {
    
    if (!_infoDicArray) {
        //        NSDictionary *dic1 = @{@"icon"      : @"credit_Card",
        //                               @"title"     : @"银行卡支付",
        //                               @"subTitle"  : @"安全快速支付，无需开通网银",};
        NSDictionary *dic2 = @{@"icon"      : @"weixin",
                               @"title"     : @"微信支付",
                               @"subTitle"  : @"推荐安装微信5.0以上版本的用户使用",};
        NSDictionary *dic3 = @{@"icon"      : @"wallet",
                               @"title"     : @"钱包支付",
                               @"subTitle"  : @"虎头奔钱包支付",};
        NSDictionary *dic4 = @{@"icon"      : @"zhifubao",
                               @"title"     : @"支付宝支付",
                               @"subTitle"  : @"推荐拥有支付宝账号的用户使用",};
        _infoDicArray = @[ dic2, dic3, dic4];
    }
    return _infoDicArray;
}

- (NSMutableArray *)selectArray {
    
    if (!_selectArray) {
        _selectArray = [[NSMutableArray alloc] init];
    }
    return _selectArray;
}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - view method
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"支付";
    
    [self addLeftBackBarButtonItem];
    
    [self.selectArray addObject:@YES];
    [self.selectArray addObject:@NO];
    [self.selectArray addObject:@NO];
    [self.selectArray addObject:@NO];
    
    [self createHeaderView];            // 计时header
    [self createTableView];             // table
//    NSLog(@"code = %@", self.payModel.code);
    
    NSTimeInterval current_time = [NSDate currentDateTimeInterval];
//    NSTimeInterval create_time = self.payModel.create_time.doubleValue;
    NSTimeInterval create_time = current_time - 0;
    
    NSTimeInterval delte = current_time - create_time;
    if (delte > 15 * 60.00f) {
        // 超时了，无法支付
        [ByCoreToolAlert showFailureWithText:@"该订单已超时，无法支付"];
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    // 开启定时器
    _second = 15 * 60 - delte;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.00 target:self selector:@selector (timeAction:) userInfo:nil repeats:YES];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(aliPaySuccess:) name:@"aliPaySuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wechatPaySuccess:) name:@"wechatPaySuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wechatPayFailure:) name:@"wechatPayFailure" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(aliPayFailure:) name:@"aliPayFailure" object:nil];
}

#pragma mark - 定时器方法
// 定时器方法
- (void)timeAction:(NSTimer *)timer {
    
    UILabel *timeBasalLabel = [self.headerView viewWithTag:10];
    
    UILabel *label1 = [timeBasalLabel viewWithTag:1];
    UILabel *label2 = [timeBasalLabel viewWithTag:2];
    UILabel *label3 = [timeBasalLabel viewWithTag:3];
    UILabel *label4 = [timeBasalLabel viewWithTag:4];
    
    _second --;
    
    NSInteger minute = _second / 60;
    NSInteger second = _second % 60;
    
    label1.text = [NSString stringWithFormat:@"%li", minute / 10];
    label2.text = [NSString stringWithFormat:@"%li", minute % 10];
    label3.text = [NSString stringWithFormat:@"%li", second / 10];
    label4.text = [NSString stringWithFormat:@"%li", second % 10];
    
    if (_second == 0) {
        [ByCoreToolAlert showFailureWithText:@"超时未支付，订单已失效"];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - 创建视图
// 创建头视图
- (void)createHeaderView {
    
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 100)];
    self.headerView.backgroundColor = TABLE_COLOR;
    [self.view addSubview:self.headerView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.headerView.width, 20)];
    titleLabel.font = FONT(14);
    titleLabel.text = @"支付剩余时间";
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.headerView addSubview:titleLabel];
    
    UILabel *timeBasalLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.headerView.width, 25)];
    timeBasalLabel.tag = 10;
    [self.headerView addSubview:timeBasalLabel];
    
    CGFloat margin = 5;
    CGFloat remine = (self.headerView.height - titleLabel.height - timeBasalLabel.height) / 2;
    titleLabel.top = remine;
    timeBasalLabel.top = titleLabel.bottom + margin;
    
    // 分：十位
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 25)];
    label1.backgroundColor = [UIColor blackColor];
    label1.font = FONT(14);
    label1.text = @"0";
    label1.textColor = [UIColor whiteColor];
    label1.textAlignment = NSTextAlignmentCenter;
    [timeBasalLabel addSubview:label1];
    label1.tag = 1;
    // 分：个位
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 25)];
    label2.backgroundColor = [UIColor blackColor];
    label2.font = FONT(14);
    label2.text = @"0";
    label2.textColor = [UIColor whiteColor];
    label2.textAlignment = NSTextAlignmentCenter;
    [timeBasalLabel addSubview:label2];
    label2.tag = 2;
    // 冒号
    UILabel *labelCenter = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 25)];
    labelCenter.backgroundColor = [UIColor clearColor];
    labelCenter.font = FONT(14);
    labelCenter.text = @":";
    labelCenter.textColor = [UIColor blackColor];
    labelCenter.textAlignment = NSTextAlignmentCenter;
    [timeBasalLabel addSubview:labelCenter];
    // 秒：十位
    UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 25)];
    label3.backgroundColor = [UIColor blackColor];
    label3.font = FONT(14);
    label3.text = @"0";
    label3.textColor = [UIColor whiteColor];
    label3.textAlignment = NSTextAlignmentCenter;
    [timeBasalLabel addSubview:label3];
    label3.tag = 3;
    // 秒：个位
    UILabel *label4 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 25)];
    label4.backgroundColor = [UIColor blackColor];
    label4.font = FONT(14);
    label4.text = @"0";
    label4.textColor = [UIColor whiteColor];
    label4.textAlignment = NSTextAlignmentCenter;
    [timeBasalLabel addSubview:label4];
    label4.tag = 4;
    
    margin = 3;
    remine = (timeBasalLabel.width - 20 * 5 - margin * 2) / 2;
    
    label1.left = remine;
    label2.left = label1.right + margin;
    labelCenter.left = label2.right;
    label3.left = labelCenter.right;
    label4.left = label3.right + margin;
}
// 创建表视图
- (void)createTableView {
    
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, self.headerView.bottom, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - self.headerView.height) style:UITableViewStylePlain];
    self.table.backgroundColor = TABLE_COLOR;
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.table.tableFooterView = [UIView new];
}


#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoDicArray.count + 1;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row < self.infoDicArray.count) {
        
        ByCellOrderPayType *cell = [tableView dequeueReusableCellWithIdentifier:@"payCell"];
        if (cell == nil) {
            cell = [[ByCellOrderPayType alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"payCell"];
            
        }
        cell.infoDic = self.infoDicArray[indexPath.row];
        
        cell.select = [self.selectArray[indexPath.row] boolValue];
        
        return cell;
    }
    else {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"okCell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"okCell"];
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            UIButton *okButton = [UIButton buttonWithType:UIButtonTypeCustom];
            okButton.frame = CGRectMake(20, 30, SCREEN_WIDTH - 40, 40);
            okButton.backgroundColor = BY_THEME_COLOR;
            [okButton setTitle:[NSString stringWithFormat:@"确认支付%@元", self.fee] forState:UIControlStateNormal];
            [okButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [okButton addTarget:self action:@selector(okAction) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:okButton];
        }
        
        return cell;
    }
    
    return [UITableViewCell new];
    
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.infoDicArray.count) {
        return 60;
    }
    else {
        return 100;
    }
    return 60;
}


// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row < self.infoDicArray.count) {
        for (int i = 0; i < self.selectArray.count; i ++) {
            if (i == indexPath.row) {
                [self.selectArray replaceObjectAtIndex:i withObject:@YES];
            } else {
                [self.selectArray replaceObjectAtIndex:i withObject:@NO];
            }
        }
        [self.table reloadData];
    }
    
    
}


#pragma mark - 点击事件
- (void)okAction {
    
    // 支付方式
    NSInteger payment = 0;
    for (int i = 0; i < 3; i++) {
        
        if ([self.selectArray[i] integerValue]) {
            payment = i;
        }
    }
    
    if (payment == 0){
        
        [self wechatPay];
        
    }else if (payment == 1){
        
        [self walletPay];
        
    }else{
        
        [self alipay];
    }
    
    
}






// 支付宝
- (void)alipay{
    
    [ByCoreToolAlert showOnlyText:@"支付宝支付"];
    
    //        if (!self.payModel.isLegal){
    //
    //            [ByCoreToolAlert showFailureWithText:@"该订单存在安全问题"];
    //            return;
    //        }
    
//    ByNetParamsModel *params = [[ByNetParamsModel alloc] init];
//    params.productDes = @"虎头奔支付";
//    params.productName = @"虎头奔支付";
//    params.tradeNO = self.payModel.code;
//    NSLog(@"tradeNO = %@", params.tradeNO);
//    params.totalFee = [NSString stringWithFormat:@"%f", self.payModel.total_price.floatValue / 100];
//    params.showUrl = @"http://domain.merchant.com/payment_notify";
//    
//    [ByNetAliPayApi AliPayGoPay:params success:^(ByNetBaseResult *result) {
//        
//    }failure:^(ByNetBaseResult *result) {
//        
//        [ByCoreToolAlert showFailureWithText:result.msg];
//        
//    }];
    
    
}


- (void)aliPaySuccess:(NSNotification *)notification {
    
    
    [self backAction:YES];
    
}

- (void)aliPayFailure:(NSNotification *)notification {
    
    
    [self backAction:NO];
}



// 微信支付
- (void)wechatPay{
    [ByCoreToolAlert showOnlyText:@"微信支付"];
    
//    ByNetWechatPayModel *payModel = [[ByNetWechatPayModel alloc] init];
//    payModel.code = self.payModel.code;
//    payModel.desc = self.payModel.desc;
//    payModel.total_price = [NSString stringWithFormat:@"%f", self.payModel.total_price.floatValue];
//    [ByCoreToolAlert showLoadind:@"正在发起支付..."];
//    [ByNetWechatPayApi wechatForePayRequest:payModel failure:^(ByNetBaseResult *result) {
//        
//        [self backAction:NO];
//    }];
    
}

- (void)wechatPaySuccess:(NSNotification *)notification {
    
    
    [self backAction:YES];
    
}

- (void)wechatPayFailure:(NSNotification *)notification {
    
    
    [self backAction:NO];
    
}

// 钱包支付
- (void)walletPay{

//    // 没有设置支付密码，直接跳转到设置支付密码界面
//    if (BY_USER.wallet_password.length == 0) {
//        
//        ByWalletPasswordManager *vc = [[ByWalletPasswordManager alloc] init];
//        [self by_normalPush:vc hasNavi:YES];
//        
//    }else{
        [self balancePay];
//    }
//    
//    NSLog(@"钱包支付");
}


// 余额支付
- (void)balancePay {
    
//    [self alertPayPswInputView];
    
    ByNetParamsModel *params = [[ByNetParamsModel alloc] init];
    params.uid = BY_USER.uid;
    params.pay_code = self.payModel.code;
    [ByCoreToolAlert showLoadind:@"正在发起支付..."];
    [ByApiPay walletPay:params success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showOnlyText:@"支付成功"];
        [self backAction:YES];
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showOnlyText:@"支付失败"];
        [self backAction:NO];
    }];
}

- (void)alertPayPswInputView {
    
//    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:@"输入您的6位支付密码" preferredStyle:UIAlertControllerStyleAlert];
//    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
//        textField.keyboardType = UIKeyboardTypeNumberPad;
//        textField.placeholder = @"输入6位支付密码";
//    }];
//    
//    // 按钮按下时，让程序读取文本框中的值
//    UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        
//        UITextField *tf = alertController.textFields.firstObject;
//        
//        ByNetParamsModel *params = [[ByNetParamsModel alloc] init];
//        params.pay_psw_old = tf.text;
//        params.uid = BY_USER.uid;
//        
//        // 验证支付密码
//        [ByCoreToolAlert showLoadind:@"正在发起支付..."];
//        [ByNetWalletApi checkPayPassword:params success:^(ByNetBaseResult *result) {
//            
//            ByNetParamsModel *params = [[ByNetParamsModel alloc] init];
//            params.uid = BY_USER.uid;
//            params.pay_code_type = self.payModel.code;
//            
//            // 支付宝支付
//            [ByNetPayApi getPayInfo:params success:^(ByNetBaseResult *result) {
//                
//                [ByCoreToolAlert showSuccessWithText:@"支付成功"];
//                
//                
//                // 支付成功
//                [self backAction:YES];
//                
//            } failure:^(ByNetBaseResult *result) {
//                [ByCoreToolAlert hideHud];
//                [ByCoreToolAlert showFailureWithText:result.msg];
//                
//                // 支付失败
//                [self backAction:NO];
//            }];
//            
//        } failure:^(ByNetBaseResult *result) {
//            
//            [ByCoreToolAlert hideHud];
//            [ByCoreToolAlert showFailureWithText:result.msg];
//            
//            // 支付失败
//            [self backAction:NO];
//            
//        }];
//        
//        
//    }];
//    UIAlertAction * backAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        
//        [ByCoreToolAlert hideHud];
//    }];
//    [alertController addAction:backAction];
//    [alertController addAction:okAction];
//    
//    [self presentViewController:alertController animated:YES completion:nil];
}



//银联支付
- (void)unionPay{
    NSLog(@"银联支付");
    
    
}


#pragma mark - 返回处理（成功或失败）
- (void)backAction:(BOOL)isSuccess {
    
    if (isSuccess) {    // 成功
        
        switch (self.type) {
            case 0:     // 购物车首次支付
            {
                [self by_normalPopVC:@"ByUIOrderCommitVC"];
            }
                break;
            case 1:     // 订单重新支付
            {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
                break;
                
            default:
                break;
        }
        if (self.successAction) {
            self.successAction();
        }
    } else {            // 失败
        
        switch (self.type) {
            case 0:     // 购物车首次支付
            {
                [self by_normalPopVC:@"ByUIOrderCommitVC"];
            }
                break;
            case 1:     // 订单重新支付
            {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
                break;
                
            default:
                break;
        }
        
        if (self.failureAction) {
            self.failureAction();
        }
    }
}


@end
